package com.project.poetry.common.aspect;

import cn.hutool.core.util.StrUtil;
import com.project.poetry.common.anno.CanOperation;
import com.project.poetry.common.constant.ConstantValue;
import com.project.poetry.common.constant.DictConstant;
import com.project.poetry.common.util.CommonUtil;
import org.aspectj.lang.JoinPoint;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Before;
import org.aspectj.lang.annotation.Pointcut;
import org.aspectj.lang.reflect.MethodSignature;
import org.springframework.stereotype.Component;

import java.lang.reflect.Method;
import java.util.Objects;

/**
 * 权限校验
 * @author mengxj
 */
@Aspect
@Component
public class HandlePower {

    @Pointcut("@annotation(com.project.poetry.common.anno.CanOperation)")
    private void cut(){
    }

    @Before("cut()")
    public void checkParam(JoinPoint point){
        Method targetMethod = ((MethodSignature)point.getSignature()).getMethod();
        CanOperation operation = targetMethod.getAnnotation(CanOperation.class);
        if(Objects.isNull(operation)){
            operation = point.getTarget().getClass().getAnnotation(CanOperation.class);
        }
        String value = operation.value();
        String powerMessage;
        if(StrUtil.EMPTY.equals(value)){
            powerMessage = ConstantValue.POWER_DEFAULT_MESSAGE;
        }else{
            powerMessage = String.format("当前用户无%s 权限", value);
        }
        CommonUtil.checkThrow(user -> !user.isVip(),
                CommonUtil.getUser(), powerMessage);
    }
}
